package com.tyf.common.web.feign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tyf.common.exception.MyselfMsgException;
import com.tyf.common.vo.ResultVO;
import feign.Response;
import feign.Util;
import feign.codec.StringDecoder;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Feign 解码器,自动判断业务异常，转换成对应对象
 */
public class EudFeignResultVoDecoder extends StringDecoder {

	@Override
	public Object decode(Response response, Type type) throws IOException {
		if (response.status() == 404)
			return Util.emptyValueOf(type);
		if (response.body() == null)
			return null;
		if (byte[].class.equals(type)) {
			return Util.toByteArray(response.body().asInputStream());
		}
		//结果集
		Response.Body body = response.body();
		/* 注释：针对data中的内容就是字符串的场景
		 * if (String.class.equals(type)) {
		      return Util.toString(body.asReader());
	    }*/
		String mapVo = Util.toString(body.asReader());
		JSONObject jsonObj = JSON.parseObject(mapVo);
		if(jsonObj == null){
			return null;
		}
		//支持格式
		/*
		 {"flag":{"resultCode":"xx","message":"xxxx222"},"data":"List<T>"}
		 */
		String resultVoStr = jsonObj.getString("flag");
		if(StringUtils.isBlank(resultVoStr)){
			return null;
		}
		//调整Myself异常的时候,不会有包含data节点，则需要调整一下代码顺序
		ResultVO vo = JSON.parseObject(resultVoStr, ResultVO.class);
		if(vo.getRetCode().equals(ResultVO.SUCCESS_CODE)){
			String dataStr = jsonObj.getString("data");
			if(StringUtils.isBlank(dataStr)){
				return Util.emptyValueOf(type);
			}
			if(String.class.equals(type)){
				return dataStr;
			}else{
				return JSON.parseObject(dataStr, type);
			}
		}else{
			//业务异常
			throw new MyselfMsgException(vo.getRetMsg());
		}
	}

}
